package com.libreaccess.reporting.utils;

/*import java.io.File;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;*/
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.naming.InitialContext;

public class Mail {
	static final Logger logger = new Logger(Mail.class);

		public static void sendMessage(UserLiferay us, String fileName, String completedReportLink, boolean isException/*, File file*/) {
		Session session = null;

		try {
			session = (Session) new InitialContext().lookup("java:/Mail");
		} catch (Exception e) {
			logger.error("Cannot lookup mail settings: "+ e.getMessage());
		}

/*		String reportName =fileName.substring(0,fileName.lastIndexOf('_'));
		System.out.println("Report Name:"+reportName);
		System.out.println("Report Name1:"+reportName.substring(0, reportName.lastIndexOf('.')));*/
		String htmlBody = isException ? 
			"There is an Error in the Report Query, please contact the System Administrator": 
			"Dear "+us.getName()+", The report "+fileName+" has been generated. Click the following link to access it: "+completedReportLink;

		
		try {
			Message msg = new MimeMessage(session);
			String sender = System.getProperty("mail.sender", "libreReporting@example.com");
			logger.debug("sender="+sender);
			msg.setFrom(new InternetAddress(sender));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(us.getEmail()));
			msg.setSubject("Libre Report");

			Multipart multipart = new MimeMultipart();

			// Part one is the text
			BodyPart bodyPart = new MimeBodyPart();
			bodyPart.setText(htmlBody);
			multipart.addBodyPart(bodyPart);

			// Part two is the attachment
/*			bodyPart = new MimeBodyPart();
			DataSource sourceFile = new FileDataSource(file);
			bodyPart.setDataHandler(new DataHandler(sourceFile));
			bodyPart.setFileName(fileName + "." + format);
			multipart.addBodyPart(bodyPart);*/
			
			msg.setContent(multipart);
			Transport.send(msg);
			logger.debug("Report was successfully generated. Notification was sent to " + us.getEmail());
		} catch (Exception ex) {
			logger.error("Cannot send mail settings: "+ ex.getMessage());
		}
	}

}
